#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "controller.h"
#include "communicationproxy.h"

#include "qextserialport/qextserialenumerator.h"

#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_enumerator = new QextSerialEnumerator;

    //Invalid under the linux system
    connect(m_enumerator, &QextSerialEnumerator::deviceDiscovered
            , this, &MainWindow::on_flushButton_clicked);
    connect(m_enumerator, &QextSerialEnumerator::deviceRemoved
            , this, &MainWindow::on_flushButton_clicked);

    connect(CInstance->communicationProxy()->communication(), &Communication::stateChanged
            , this, &MainWindow::onSrialPortStateChanged);

    on_flushButton_clicked();
    onSrialPortStateChanged(Communication::UnconnectedState);
}

MainWindow::~MainWindow()
{
    delete ui;
    delete m_enumerator;
}

void MainWindow::on_kpLineEdit_editingFinished()
{
    CInstance->setkp(ui->kpLineEdit->text().trimmed().toFloat());
}

void MainWindow::on_kiLineEdit_editingFinished()
{
    CInstance->setki(ui->kiLineEdit->text().trimmed().toFloat());
}

void MainWindow::on_kdLineEdit_editingFinished()
{
    CInstance->setkd(ui->kdLineEdit->text().trimmed().toFloat());
}

void MainWindow::on_targetLineEdit_editingFinished()
{
    CInstance->setTarget(ui->targetLineEdit->text().trimmed().toFloat());
}

void MainWindow::on_closeButton_clicked()
{
    if (CInstance->communicationProxy()->isValid()) {
        CInstance->communicationProxy()->disconnectFromHost();
    }
}

void MainWindow::on_openButton_clicked()
{
    QString portName = ui->comboBox->currentText();
    if (portName.isEmpty()) {
        return;
    }

    if (CInstance->communicationProxy()->isValid()) {
        CInstance->communicationProxy()->disconnectFromHost();
    }

    CInstance->communicationProxy()->connectToHost(portName);
}

void MainWindow::on_flushButton_clicked()
{
    ui->comboBox->clear();

    QList<QextPortInfo> infos = QextSerialEnumerator::getPorts();
    for (int i=0; i<infos.size(); ++i) {
        QextPortInfo info = infos.at(i);
        const QString text = QString("%1").arg(info.portName);
        ui->comboBox->addItem(text);
    }
}

void MainWindow::onSrialPortStateChanged(int state)
{
    switch (state) {
    case Communication::UnconnectedState:
        ui->closeButton->setEnabled(false);
        ui->openButton->setEnabled(true);
        break;
    case Communication::ConnectedState:
        ui->closeButton->setEnabled(true);
        ui->openButton->setEnabled(false);
        break;
    case Communication::ClosingState:
    case Communication::ConnectingState:
        ui->closeButton->setEnabled(false);
        ui->openButton->setEnabled(false);
        break;
    default:
        break;
    }
}
